/*
 * @Descripttion: 
 * @version: 
 * @Author: cc
 * @Date: 2023-05-04 13:00:02
 */

const work = require('../router_handle/addfriend')
const group = require('../router_handle/chat')

module.exports = function (io) {
    let users = {}  //socket注册用户
    io.on("connection", (socket) => {
        //用户登录注册
        socket.on('login', (id) => {
            // console.log(socket.id)
            //回复客户端
            socket.emit('login', socket.id)
            socket.name = id  //保存这个传入的用户id
            users[id] = socket.id  //以键值对的形式存储对应的socket id
        })


        //一对一消息发送
        socket.on('Msg', (msg, fromid, toid) => {
            //修改好友最后通讯时间
            //work.updateFriendLastTime(fromid, toid)
            // //存储一对一消息
            //work.insertMsg(fromid, toid, msg.message, msg.types)
            console.log(users);
            if (users[toid]) { //如果用户登录了
                //发送给对方用户 0发送给对方 1发送给自己
                socket.to(users[toid]).emit('msg', msg, fromid, 0)
            }
            // console.log('fromid, toid',fromid, toid);
            //发送给自己
            socket.emit('msg', msg, toid, 1)
        })

        //用户离开
        socket.on("disconnecting", () => {
            //判断用户中是否有这个socket
            if (users.hasOwnProperty(socket.name)) {
                delete users[socket.name]
                console.log(socket.id + '离开');
            }
        });

        //加入群
        socket.on('group', (groupid) => {
            socket.join(groupid)
            console.log('---------');
            console.log(socket.rooms);
        })

        //接收群消息
        socket.on('groupMsg', (msg, fromid, gid, name, avater) => {
            // console.log('触发了');
            console.log('gid', gid);
            //在某群广播消息  发给对方
            // console.log(msg, fromid, gid, name, avater);
            //存储群消息
            group.addGroupMsg(gid, fromid, msg.message, msg.types)

            socket.to(gid).emit('groupmsg', msg, fromid, gid, name, avater, 0)

            //同时发送一份给自己
            socket.emit('groupmsg', msg, fromid, gid, name, avater, 1)
        })

        //告知离开当前聊天页面
        socket.on('leaveChat', (uid, fid, flag) => {
            //0表示个人 1表示群
            socket.emit('leavechat', uid, fid, flag)
        })

    });
}
